package com.test.controller;

import com.test.model.User;
import com.test.service.UserService;
import io.shardingsphere.core.api.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping(path = "/{userId}", method = {RequestMethod.GET})
    public User getUserByUserId(@PathVariable("userId") Integer userId) {
        return userService.getUserByUserId(userId);
    }

    @RequestMapping(method = {RequestMethod.GET})
    public List<User> getUsers() {
        HintManager.getInstance().setMasterRouteOnly();
        return userService.getUsers();
    }

    @RequestMapping(path = "/master/{userId}", method = {RequestMethod.GET})
    public User getUserByUserIdFromMaster(@PathVariable("userId") Integer userId) {
        return userService.getUserByUserIdFromMaster(userId);
    }

    @RequestMapping(method = {RequestMethod.POST})
    public String createUser() {
        User user = new User();
        int id = redisTemplate.boundValueOps("user_key").increment(1l).intValue();
        user.setUserId(id);
        user.setUserName(UUID.randomUUID().toString());
        userService.createUser(user);
        return "success";
    }

}
